package com.zhexiao.convert.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zhexiao.convert.base.Result;
import com.zhexiao.convert.component.UploadFile;
import com.zhexiao.convert.config.AppConfig;
import com.zhexiao.convert.entity.dto.ConvertDTO;
import com.zhexiao.convert.entity.postman.Postman;
import com.zhexiao.convert.service.ConvertService;
import com.zhexiao.convert.component.ReadFile;
import com.zhexiao.convert.utils.PostmanWord;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;


/**
 * @author zhexiao
 * @date 2020-09-15 22:17
 * @description
 */
@Service
public class ConvertServiceImpl implements ConvertService {

    private static final Logger log = LoggerFactory.getLogger(ConvertServiceImpl.class);

    @Autowired
    AppConfig appConfig;

    @Autowired
    ReadFile readFile;

    @Autowired
    UploadFile uploadFile;


    /**
     * 解析上传的文件数据
     *
     * @param file
     * @return
     */
    @Override
    public Result<Postman> upload(MultipartFile file) {
        Postman postman = this.parsePostmanJson(file);
        return Result.success(postman);
    }

    /**
     * 生成word数据
     *
     * @param file
     * @return
     * @throws Exception
     */
    @Override
    public Result<String> writeWord(MultipartFile file, ConvertDTO convertDTO) {
        //postman数据解析到对象
        Postman postman = this.parsePostmanJson(file);

        //保存文件
        String filename = postman.getInfo().getName() + "_" + System.currentTimeMillis() + ".docx";
        String dest = appConfig.getFileDest() + File.separator + filename;

        new PostmanWord(postman).generate(convertDTO).save(dest);
        log.info("---------------word导出完毕--------------");

        return Result.success(dest);
    }

    /**
     * 通过文件读取数据
     *
     * @param file
     * @return
     */
    private Postman parsePostmanJson(MultipartFile file) {
        String res = readFile.read(file);

        JSONObject jsonObject = JSON.parseObject(res);
        return JSON.toJavaObject(jsonObject, Postman.class);
    }
}
